package org.test.httpclient;

import java.net.URI;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.test.mail.MailConstant;

import com.google.gson.Gson;

public class AppleClient extends Thread {
	private static Log log=LogFactory.getLog(AppleClient.class);

	@Override
	public void run() {
		try {
			getAppleStatus();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args){
		AppleClient client = new AppleClient();
		client.start();//而不是调用run方法
		System.out.println("main done!!!");
	}

	private void getAppleStatus(){
		while (true) {
			try {
				URI uri = URIUtils.createURI("http", "store.apple.com", 80, "/cn/variationUpdate/IPHONE4S",
						"option.dimensionColor=white&option.dimensionCapacity=16gb&carrierPolicyType=UNLOCKED", null);
				HttpGet httpget = new HttpGet(uri);
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response = httpclient.execute(httpget);
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					long len = entity.getContentLength();
					if (len != -1 && len < 2048) {
						Gson gson = new Gson();
						AppleJson apple = gson.fromJson(EntityUtils.toString(entity), AppleJson.class);
						if (apple.getBody().getContent().getSelected().getPurchaseOptions().isBuyable()) {
							log.info("OK");
							Email email = new SimpleEmail();
							email.setHostName("smtp.sina.com");
							email.setSmtpPort(25);
							email.setTLS(true);
							email.setFrom("chenk008@sina.com.cn");
							email.setAuthentication(MailConstant.USER_NAME, MailConstant.PASSWORD);

							email.setSubject("apple ok");
							email.setMsg(EntityUtils.toString(entity));

							email.addTo("kongchen28@gmail.com");

							email.send();
						}
					}
				}
			} catch (Exception e) {
				log.error("apple eroor!!!", e);
			} 
		}
	}
}
